#include "mtp_pwm.h"
#include "ad5274_5271.h"
#include "iic_current.h"
#include "sys.h"
#include "math.h"

TIM_HandleTypeDef TIM12_Handler;         //定时器句柄 
TIM_OC_InitTypeDef TIM12_CH2Handler;     //定时器1通道3句柄

#define DELAY_TIME 3				 //03-15修改为3，之前为6；使用正常；

BYTE AD5272_pucData[2];


void OTP_EN_IO_init(void)
{
    GPIO_InitTypeDef GPIO_Initure;
	__HAL_RCC_GPIOG_CLK_ENABLE();			//GPIOG
	
	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     //高速
	GPIO_Initure.Pull =GPIO_PULLUP;
	GPIO_Initure.Mode = GPIO_MODE_OUTPUT_PP;	
	GPIO_Initure.Pin = OTP_EN;				
	HAL_GPIO_Init(OTP_EN_GPIO,&GPIO_Initure); 	
	OTP_EN_LOW;
	
//	__HAL_RCC_GPIOF_CLK_ENABLE();			//GPIOF	
//	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     //高速
//	GPIO_Initure.Pull =GPIO_PULLDOWN;
//	GPIO_Initure.Mode = GPIO_MODE_INPUT;	
//	GPIO_Initure.Pin = GPIO_PIN_10;				
//	HAL_GPIO_Init(GPIOF,&GPIO_Initure); 		
	
}

//TIM1 PWM部分初始化 
//PWM输出初始化
//arr：自动重装值
//psc：时钟预分频数
void TIM12_PWM_Init(u16 arr,u16 psc)
{ 
    TIM12_Handler.Instance=TIM12;            //定时器3
    TIM12_Handler.Init.Prescaler=psc;       //定时器分频
    TIM12_Handler.Init.CounterMode=TIM_COUNTERMODE_UP;//向上计数模式
    TIM12_Handler.Init.Period=arr;          //自动重装载值
    TIM12_Handler.Init.ClockDivision=TIM_CLOCKDIVISION_DIV1;
    HAL_TIM_PWM_Init(&TIM12_Handler);       //初始化PWM
    
    TIM12_CH2Handler.OCMode=TIM_OCMODE_PWM1; //模式选择PWM1
    TIM12_CH2Handler.Pulse=arr/2;            //设置比较值,此值用来确定占空比，
                                            //默认比较值为自动重装载值的一半,即占空比为50%
    TIM12_CH2Handler.OCPolarity=TIM_OCPOLARITY_LOW; //输出比较极性为低 
    HAL_TIM_PWM_ConfigChannel(&TIM12_Handler,&TIM12_CH2Handler,TIM_CHANNEL_2);//配置TIM3通道4
    HAL_TIM_PWM_Start(&TIM12_Handler,TIM_CHANNEL_2);//开启PWM通道3
}

//定时器底层驱动，时钟使能，引脚配置
//此函数会被HAL_TIM_PWM_Init()调用
//htim:定时器句柄
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
    GPIO_InitTypeDef GPIO_Initure;
	  __HAL_RCC_TIM12_CLK_ENABLE();			//使能定时器1
    __HAL_RCC_GPIOB_CLK_ENABLE();			//开启GPIOB时钟
	
    GPIO_Initure.Pin=GPIO_PIN_15;           	//PB15
    GPIO_Initure.Mode=GPIO_MODE_AF_PP;  	//复用推完输出
    GPIO_Initure.Pull=GPIO_PULLUP;          //上拉
    GPIO_Initure.Speed=GPIO_SPEED_HIGH;     //高速
	  GPIO_Initure.Alternate=GPIO_AF9_TIM12;	//PB15复用为TIM1_CH3N
    HAL_GPIO_Init(GPIOB,&GPIO_Initure);
}

//设置TIM通道4的占空比
//compare:比较值
void TIM_SetTIM12Compare2(u32 compare)
{
	TIM12->CCR2=compare; 
}
int compare;
void OTP_POWER_Init(double volt,u8 flag)
{
	 //duty range: 350~500  \volt output: 5.5~10v	
	compare=volt<3.5?250:volt>10?550:(volt+3.899)/0.0295;
	TIM_SetTIM12Compare2(compare);
	if(flag)
		OTP_EN_LOW;
	else
		OTP_EN_HIGH;
}



//----------------硬件改版-------------------------

void AD5272_I2CSDASetInput(void); // Set I2C SDA signal as input
void AD5272_I2CSDASetOutput(void); // Set I2C SDA signal as output

void AD5272_GPIO_Config(void)
{
	GPIO_InitTypeDef GPIO_Initure;  	
  __HAL_RCC_GPIOG_CLK_ENABLE(); 
	
	GPIO_Initure.Pin = AD5272_PIN_SCL;		
	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     
	GPIO_Initure.Pull =GPIO_PULLUP;
	GPIO_Initure.Mode = GPIO_MODE_OUTPUT_PP;	
	HAL_GPIO_Init(AD5272_GPIO_SCL,&GPIO_Initure); 	 
	
	GPIO_Initure.Pin = AD5272_PIN_SDA;		
	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     
	GPIO_Initure.Pull =GPIO_PULLUP;
	GPIO_Initure.Mode = GPIO_MODE_OUTPUT_PP;	
	HAL_GPIO_Init(AD5272_GPIO_SDA,&GPIO_Initure); 	
}

void AD5272_I2CSDASetInput(void)
{
	GPIO_InitTypeDef GPIO_Initure; 	
	GPIO_Initure.Pin = AD5272_PIN_SDA;		
	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     
	GPIO_Initure.Pull =GPIO_PULLUP;
	GPIO_Initure.Mode = GPIO_MODE_INPUT;	
	HAL_GPIO_Init(AD5272_GPIO_SDA,&GPIO_Initure); 
} 
void AD5272_I2CSDASetOutput(void)
{ 
	GPIO_InitTypeDef GPIO_Initure; 	
	GPIO_Initure.Pin = AD5272_PIN_SDA;		
	GPIO_Initure.Speed= GPIO_SPEED_HIGH;     
	GPIO_Initure.Pull =GPIO_PULLUP;
	GPIO_Initure.Mode = GPIO_MODE_OUTPUT_PP;	
	HAL_GPIO_Init(AD5272_GPIO_SDA,&GPIO_Initure); 
}

// Start bit of I2C waveform
void AD5272_I2CStart(void)
{
    AD5272_I2CSDASetOutput();
    AD5272_SDA_H; 
    AD5272_SCL_H;
		TWait();
    AD5272_SDA_L; 
		TWait();
    AD5272_SCL_L; 
}

// Stop bit of I2C waveform
void AD5272_I2CStop(void)
{
    AD5272_I2CSDASetOutput();
    AD5272_SCL_H;
    AD5272_SDA_L;
    AD5272_SCL_H;
    TWait();
    AD5272_SDA_H;
    TWait();
}

// Send one byte from host to client
bool AD5272_I2CSendByte(BYTE ucData)
{
	bool bRet;
	unsigned char i=8; 
	AD5272_I2CSDASetOutput();
	do{
		if (ucData&0x80)
			AD5272_SDA_H;
			else 
			AD5272_SDA_L;
		TWait();//-----------------------????
		AD5272_SCL_H;
		TWait();
		ucData<<=1;
		AD5272_SCL_L;
			if (i>1) //判断是否传递最后一位数据，若是最后一位则TSCL拉低后不用等待
		TWait();
    }while(--i);
	
	AD5272_I2CSDASetInput();

	bRet=FALSE;
	AD5272_SCL_H;
	TWait();
	if (HAL_GPIO_ReadPin(AD5272_GPIO_SDA, AD5272_PIN_SDA))
		bRet=TRUE;
	AD5272_SCL_L;
	TWait();
	return bRet;
}
  
// Receive one byte form client to host
BYTE AD5272_I2CReciveByte(bool bAck)
{
	BYTE ucRet,i;
  
	AD5272_I2CSDASetInput();
	ucRet = 0;
	i=8;
	do
	{	AD5272_SCL_H;
		TWait();
		ucRet<<=1;
		if(HAL_GPIO_ReadPin(AD5272_GPIO_SDA, AD5272_PIN_SDA))
			ucRet++;
		AD5272_SCL_L;
                if (i>1) //判断是否传递最后一位数据，若是最后一位则TSCL拉低后不用等待
		TWait();
	}while(--i);

	AD5272_I2CSDASetOutput();

	if (bAck==0)			//这里可能需要调整
    AD5272_SDA_L;
	else AD5272_SDA_H;

	AD5272_SCL_H;
	TWait();
	AD5272_SCL_L;
	TWait();         
	return ucRet;
}

// I2C send data fuction
bool AD5272_I2CSend(BYTE ucDeviceAddr, BYTE ucIndex, u16 RDACValue)
{
      bool bRet = TRUE;

      AD5272_I2CStart();

      if(AD5272_I2CSendByte(ucDeviceAddr & 0xFE) == ACK)
        {
          ucIndex = (ucIndex<<2) + ((RDACValue>>8)&0x03);

		    if(AD5272_I2CSendByte(ucIndex) == ACK)
            {
                  if(AD5272_I2CSendByte(RDACValue&0xff) == NAK)
                  {
                    bRet = FALSE;
                  }
            }
          else
            {
             bRet = FALSE;
            }
        }
      else
      {
      	bRet = FALSE;
      }
      AD5272_I2CStop();
      return bRet;
}
// I2C receive data function
bool AD5272_I2CReceive(BYTE ucDeviceAddr, BYTE ucIndex, BYTE* AD5272_pucData, unsigned int unDataLength) //(器件地址，buffer类型，被读出数据保存位置，读出数据长度)
{
    unsigned int i;
    bool bRet = TRUE;
    AD5272_I2CStart();
    if(AD5272_I2CSendByte(ucDeviceAddr & 0xFE) == ACK)//FRAME 1 SERIAL BUS ADDRESS BYTE   WRITE 0
        {
			ucIndex = (ucIndex<<2);
				//	+ AD5272_pucData[0];
			if(AD5272_I2CSendByte(ucIndex) == ACK)   //FRAME 2 MOST SIGNIFICANT DATA BYTE
			{
			   if(AD5272_I2CSendByte(AD5272_pucData[0]) == ACK)  //FRAME 3 LEAST SIGNIFICANT DATA BYTE
				{
					AD5272_I2CStop();		 
					AD5272_I2CStart();
					if(AD5272_I2CSendByte(ucDeviceAddr | 0x01) == ACK)   //READ 1
					{
						for(i = 0; i < unDataLength-1; i++)
						{  AD5272_pucData[i] = AD5272_I2CReciveByte(ACK);
						}
						AD5272_pucData[unDataLength - 1] = AD5272_I2CReciveByte(NAK);
					}
					else
					{          bRet = FALSE;           }
				}
				else
				{          bRet = FALSE;           }
			}
			else
			{           bRet = FALSE;           }
		}
		else
        {           bRet = FALSE;           }
    AD5272_I2CStop();
    return bRet;
}

void VPP_AD5272_Init(u16 uvol)
{	
	DelayMs(10);
	AD5272_I2CSend(DEVICE_ADDRESS_VPP, COMMAND_WRITE_CONTROL_INDEX, 3);
	DelayMs(10);	
	AD5272_I2CSend(DEVICE_ADDRESS_VPP, COMMAND_WRITE_RDAC_INDEX, uvol);
	DelayMs(10);		
}

void VPP_POWER_Init(double volt, u8 flag)
{
	double set_value=0;
	if(volt>7.5)
	{
		volt=7.5;
	}
	else if(volt<4.0)
	{
		volt=4.0;
	}
	OTP_EN_LOW;
	DelayMs(10);
	set_value=3461*pow(volt,-1.473)-178.1;
	VPP_AD5272_Init(set_value);
	if(flag)
		OTP_EN_HIGH;
	else
		OTP_EN_LOW;
}
